from utils.config import settings
from contextlib import asynccontextmanager
from fastapi import FastAPI
from fastapi.staticfiles import StaticFiles
from internal.auth import router as auth_router
from middleware.cors_middleware import add_cors_middleware
import logging
from sqlmodel import SQLModel, Session, select
from dependencies.database import engine
from models.auth import UserDB

# 配置日志
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
logging.getLogger("passlib").setLevel(logging.WARNING)

# 定义 lifespan 事件处理函数
@asynccontextmanager
async def lifespan(app: FastAPI):
    # 应用启动时执行
    logging.info("应用启动中...")

    # 创建所有定义的表
    SQLModel.metadata.create_all(engine)
    logging.info("数据库表已创建（如果不存在）")

    # 检查并插入初始用户
    with Session(engine) as session:
        # 检查是否存在 username 为 'admin' 的用户
        admin_user = session.exec(select(UserDB).where(UserDB.username == 'admin')).first()
        if not admin_user:
            # 创建初始用户
            new_user = UserDB(
                username='admin',
                password='123456',  # 模型内已经加密了
                age=18,
                gender=1,
                email='admin@example.com',
                address='北京市',
                status=1,
                avatar='https://pic.nximg.cn/file/20220712/10673188_144122796123_2.jpg'
            )
            session.add(new_user)
            session.commit()
            logging.info("初始用户 'admin' 密码 '123456' 创建成功")
        else:
            logging.info("初始用户 'admin' 已存在，跳过创建")

        # 路由日志记录
        logging.info("注册的路由:")
        for route in auth_router.routes:
            logging.info(f"Path: {route.path}, Method: {route.methods}")

    # 应用关闭时执行
    try:
        yield
    finally:
        logging.info("应用关闭中...")
        # 在这里可以添加关闭时的清理操作（如果需要）

app = FastAPI(
    title="管理系统后端",
    summary="Geeker-Admin配套Fastapi后端",
    version="0.1.1",
    contact={
        "name": "星辰下的清真",
        "url": "https://blog.csdn.net/geyaliang",
        "email": "geyaliang@163.com",
    },
    openapi_tags=[
        {
            "name": "认证和用户信息",
            "description": "管理Token及用户的创建、读取。",
        },
        {
            "name": "BigAIModer",
            "description": "AI大模型。",
        },
    ],
    lifespan=lifespan
)

# 注册全局异常处理器（处理所有异常类型）
# @app.exception_handler(Exception)
# async def global_exception_handler(request: Request, exc: Exception):
#     pass

# 添加 CORS 中间件
add_cors_middleware(app)

# 配置静态文件目录
app.mount("/static", StaticFiles(directory="static"), name="static")

app.include_router(auth_router, prefix="/geeker", tags=["认证和用户信息"])

if __name__ == "__main__":
    import uvicorn

    uvicorn.run(
        "main:app",
        host=settings.SERVER_HOST,
        port=settings.SERVER_PORT,
        reload=True
    )
